package com.greate.community.util;

import com.greate.community.controller.LoginController;
import lombok.Data;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Lazy;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.Properties;
import java.util.Random;

/**
 * 类名称：MailUtil
 * 类描述：邮件服务工具类
 * 创建人：CSUpipixia
 * 创建时间：2022/1/23 13:34
 *
 * @version v1.0
 */
@Data
@Component
public class EmailUtil {

    private static final Logger logger = LoggerFactory.getLogger(LoginController.class);

    private static final String SUBJECT_REGISTER = "注册验证码";

    private static final String SUBJECT_FORGETPASSWORD = "找回密码";

    @Value("${spring.mail.username}")
    private String username;

    @Value("${spring.mail.password}")
    private String password; // 授权码

    @Value("${spring.mail.host}")
    private String host; // 服务器地址

    @Value("${spring.mail.personal}")
    private String personal; // 别名

    @Value("${spring.mail.code-expiration}")
    private Long codeExpiration; // 过期时间

    @Value("${spring.mail.reg-header}")
    private String regHeader;

    @Value("${spring.mail.forget-password-header}")
    private String forgetPasswordHeader;

    @Autowired
    @Lazy
    private RedisTemplate redisTemplate;

    /**
     * 发送注册邮箱验证码
     * @param receiver
     * @return
     */
    public String sendRegistrationCode(String receiver) {

        String code = getRandomString(6);

        String content = getResigerEmail(receiver, code);

        sendEmail(receiver, SUBJECT_REGISTER ,content);

        return code;
    }

    /**
     * 发送找回密码邮箱验证码
     * @param receiver
     * @return
     */
    public String sendRetrievePasswordCode(String receiver) {

        String code = getRandomString(6);

        String content = getRetrievePasswordEmail(receiver, code);

        sendEmail(receiver, SUBJECT_FORGETPASSWORD, content);

        return code;
    }

    /**
     * 注册邮箱模板
     * @param receiver
     * @param code
     * @return
     */
    private String getResigerEmail(String receiver, String code) {
        String[] tos = receiver.split("@");
        String sub = tos[0].substring(0,2);
        String email = sub+"*******@"+tos[1];
        String html =
                "<h4 style=\"color:#2672EC;font-size: 40px;margin-top: 24px;font-weight: normal;\">账号注册验证码</h4>" +
                        "<div style=\"margin-top: 40px;\">您好，您正在使用<a href=\"javascript:;\" target=\"_blank\" style=\"color: #2672EC;text-decoration: none;\">"+email+"</a>注册账号。</div>" +
                        "<div style=\"margin-top: 30px;\">您的注册验证码为：<em style=\"font-style: normal;font-weight: 600;\">"+code+"</em></div>" +
                        "<div style=\"margin-top: 35px;\">谢谢！</div>" +
                        "</div>";
        return html;
    }

    /**
     * 注册邮箱模板
     * @param receiver
     * @param code
     * @return
     */
    private String getRetrievePasswordEmail(String receiver, String code) {
        String[] tos = receiver.split("@");
        String sub = tos[0].substring(0,2);
        String email = sub+"*******@"+tos[1];
        String html =
                "<h4 style=\"color:#2672EC;font-size: 40px;margin-top: 24px;font-weight: normal;\">找回密码验证码</h4>" +
                        "<div style=\"margin-top: 40px;\">您好，您正在使用<a href=\"javascript:;\" target=\"_blank\" style=\"color: #2672EC;text-decoration: none;\">"+email+"</a>找回密码。</div>" +
                        "<div style=\"margin-top: 30px;\">您的找回密码验证码为：<em style=\"font-style: normal;font-weight: 600;\">"+code+"</em></div>" +
                        "<div style=\"margin-top: 35px;\">谢谢！</div>" +
                        "</div>";
        return html;
    }

    /**
     * 获得固定长度的字符串充当验证码
     * @param length
     * @return
     */
    private static String getRandomString(int length) {
        String str = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        Random random = new Random();
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < length; i++) {
            int number = random.nextInt(str.length());
            sb.append(str.charAt(number));
        }
        return sb.toString();
    }

    private void sendEmail(String receiver, String subject, String content) {
        try {
            Properties properties = new Properties();
            properties.setProperty("mail.transport.protocol", "smtp");
            properties.setProperty("mail.smtp.host", host);
            properties.setProperty("mail.smtp.auth", "true");
            Session session = Session.getInstance(properties);

            Transport transport = session.getTransport();

            MimeMessage mimeMessage = new MimeMessage(session);

            // 发件人,可以设置发件人的别名
            mimeMessage.setFrom(new InternetAddress(username, personal,"UTF-8"));
            // 收件人
            mimeMessage.setRecipient(MimeMessage.RecipientType.TO, new InternetAddress(receiver));
            // 主题
            mimeMessage.setSubject(subject);
            // 容器类 附件
            MimeMultipart mimeMultipart = new MimeMultipart();
            // 可以包装文本,图片,附件
            MimeBodyPart bodyPart = new MimeBodyPart();
            // 设置内容 getEmailHtml是邮箱内容模板
            bodyPart.setContent(content, "text/html; charset=UTF-8");
            mimeMultipart.addBodyPart(bodyPart);
            // 添加图片&附件
//            bodyPart = new MimeBodyPart();
//            bodyPart.attachFile(fileSrc);
//            mimeMultipart.addBodyPart(bodyPart);
            mimeMessage.setContent(mimeMultipart);

            // 时间
            mimeMessage.setSentDate(new Date());
            mimeMessage.saveChanges();

            transport.connect(username, password);
            transport.sendMessage(mimeMessage, mimeMessage.getAllRecipients());

            transport.close();

        } catch (UnsupportedEncodingException | MessagingException e) {
            logger.error("发送"+ subject +"邮件失败："+ receiver +" ----"+e.getMessage());
        }
    }
}
